package com.ctsi.offlinesupport.service;


import com.ctsi.commons.util.StringUtil;
import com.ctsi.commons.util.UtilDateTime;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.mybatis.support.MybatisGenericDao;
import com.ctsi.framework.mybatis.support.VoTemplate;
import com.ctsi.offlinesupport.app.rest.reponse.ApplyUserInfoResponse;
import com.ctsi.offlinesupport.app.rest.reponse.BaseSupportInfoResponse;
import com.ctsi.offlinesupport.app.rest.reponse.UserFineshedTaskResponse;
import com.ctsi.offlinesupport.constant.FlowStatusConstant;
import com.ctsi.offlinesupport.constant.SupportFlowConstant;
import com.ctsi.offlinesupport.dto.SupportInfoDTO;
import com.ctsi.organise.common.api.PersonServiceProxy;
import com.ctsi.organise.common.model.Person;
import com.ctsi.supportflow.app.entity.CustomEntity;
import com.ctsi.supportflow.app.entity.ProjectEntity;
import com.ctsi.supportflow.app.entity.SupportInfo;
import com.ctsi.system.service.api.DictionaryServiceProxy;
import com.ctsi.system.service.api.DictionayTreeServiceProxy;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * SupportFlowInfo Service 类
 * @author   liuhx
 * @description  SupportFlowInfo
 * @created	 Fri Oct 12 11:27:30 CST 2018
 */
@Service
public class SupportFlowInfoService {
	private static final Logger logger=LoggerFactory.getLogger(SupportFlowInfoService.class);

	@Autowired
	private MybatisGenericDao dao;

	@Autowired
    private PersonServiceProxy userServiceProxy;
	@Autowired
    private TaskService taskService;
	@Autowired
	private VoTemplate voTemplate;
	@Autowired
    private FlowSecuritySerivice flowSecuritySerivice;

    /**
     * 用户已办任务
     * @param param
     * @param start
     * @param pageSize
     * @return
     */
	public Page<UserFineshedTaskResponse> userFineshedTask(Map<String,Object> param, int start, int pageSize){
        if(pageSize<0||pageSize>2000) {
            pageSize=Page.DEFAULT_PAGE_SIZE;
        }
        if(start!=-1) {
            Page<SupportInfoDTO> responses =  dao.queryPage(SupportInfo.class.getName()+".userFineshedTask", param, start, pageSize);

           List<UserFineshedTaskResponse> rr =  responses.getResult().stream().map(result -> {
               List<Task> tasks = taskService.createTaskQuery().processInstanceId(result.getProcessInstId()).list();
               if (UtilValidate.isNotEmpty(tasks)) {
                   Set<String> userNames = new HashSet<>();
                   Set<String> actNames = new HashSet<>();
                   for (Task task : tasks) {
                       String userId = task.getAssignee();
                       Person user = userServiceProxy.findPersonById(userId);
                       if (user != null ) {
                           userNames.add(user.getFullName());

                       } else {
                           logger.error("can not find user for userId {}",userId);
                       }
                       actNames.add(task.getName());
                   }
                   result.setNextProcessor(StringUtil.join(new ArrayList<>(userNames),","));
                   result.setNextActivityName(StringUtil.join(new ArrayList<>(actNames)," / "));
               }
               UserFineshedTaskResponse response = new UserFineshedTaskResponse();
               response = voTemplate.defaultExcute(response,toBaseSupportInfo(result));
               ApplyUserInfoResponse userInfo = toUserInfoRel(result);
               response.setNextActivityName(result.getNextActivityName());
               response.setNextProcessor(result.getNextProcessor());
               response.setBusinesskey(result.getId());
               response.setProcessInstId(result.getProcessInstId());
               response.setUserInfo(userInfo);
               response.setActivityName(result.getCurActivityName());
               response.setTaskId(result.getTaskId());
                return response;
            }).collect(Collectors.toList());

            return new Page<>(start,responses.getTotalCount(),pageSize,rr);
        } else{
            throw new RuntimeException("参数不正确 !!");
        }
    }

    @Autowired
    private DictionaryServiceProxy dictionaryServiceProxy;
	@Autowired
    private DictionayTreeServiceProxy dictionayTreeServiceProxy;
	@Autowired
    private ProjectEntityService projectEntityService;
	@Autowired
    private CustomEntityService customEntityService;

    /**
     * 累赘 但是不能删除
     * @param result
     * @return
     */
    private BaseSupportInfoResponse toBaseSupportInfo(SupportInfoDTO result) {
        BaseSupportInfoResponse response = new BaseSupportInfoResponse();

        response.setCustomGroupId(result.getCustomGroupId());
        response.setServiceType(result.getSeviceType());
        response.setServiceTypeName(this.dictionaryServiceProxy.getDictValue(SupportFlowConstant.SUPPORT_SERVICE_TYPE, result.getSeviceType()));
        if (result.getFlowStartTime() != null ) {
            response.setFlowStartTime(UtilDateTime.longToString(result.getFlowStartTime(), "yyyy-MM-dd")); // 流程开始时间
        }
        if(result.getSubmitTime()!= null){
            response.setSubmitTimeStr(UtilDateTime.longToString(result.getSubmitTime(),"yyyy-MM-dd")); // 支撑单提交时间
        }
        response.setSupportType(result.getSupportType());
        List<String> serviceTypeNames = this.dictionayTreeServiceProxy.getTreeDataNameChain(SupportFlowConstant.SUPPORT_TYPE_TYPE, result.getSupportType());
        response.setSupportTypeName(StringUtil.join(serviceTypeNames, "/"));

        response.setProjectRequirement(result.getProjectRequirement());
        response.setProcessInstanceId(result.getProcessInstId());

        response.setSupportNum(result.getSupportNum());
        // 处理项目客户信息
        response.setCustomName(result.getCustomName());
        response.setCustomGroupId(result.getCustomGroupId());

        // 处理项目信息
        ProjectEntity project = projectEntityService.findProjectEntityById(result.getCustomGroupId());

        if (project != null) {
            response.setProjectName(project.getProjectName());
            response.setIsSign(project.getIsSign());
            response.setIsSignStr(project.getIsSign() == 0? "未签约":"已签约");
        }

        CustomEntity custom = customEntityService.findCustomEntityById(result.getCustomName());

        if (custom != null) {
            response.setCustomNameStr(custom.getCustomName());
        }

        response.setBusinessKey(result.getId());
        response.setRequiredFinshtime(UtilDateTime.longToString(result.getRequiredFinshtime(),"yyyy-MM-dd"));

        if (result.getIsAuto() == 0) {
            response.setIsSignStr("政支主任派单");
        }else if(result.getIsAuto() == 1) {
            response.setIsSignStr("自动派单");
        }else if (result.getIsAuto() == 2) {
            response.setIsSignStr("指定支撑经理派单");
        }

        response.setIsAunto(result.getIsAuto());
//        response.setIsStandard(result.getStandard());
//        response.setIsStandardStr(result.getStandard() == 1 ? "是" : "否");
        //处理流程信息
        int flowStatusId = result.getCurFlowStatus();
        response.setStatusId(flowStatusId);
        if (flowStatusId == FlowStatusConstant.NOSTART.value) {
            response.setStatusName(FlowStatusConstant.NOSTART.lable);
        } else if (flowStatusId == FlowStatusConstant.STARTED.value) {
            response.setStatusName(FlowStatusConstant.STARTED.lable);
        } else if (flowStatusId == FlowStatusConstant.COMPLETE.value) {
            response.setStatusName(FlowStatusConstant.COMPLETE.lable);
        }
        response.setCurActitityName(result.getCurActivityName());
        response.setCurActivityId(result.getCurActivityId());
        // TODO: 设置是否是回退环节
        response.setIsReported(result.getIsReported());
        if (result.getIsReported() != null) {
            response.setIsReportedStr(result.getIsReported() == 0 ? "否" : "是");
        }
        return response;
    }

    /**
     * 转换用户信息
     * @param supportInfo
     * @return
     */
    private ApplyUserInfoResponse toUserInfoRel(SupportInfoDTO supportInfo) {
        ApplyUserInfoResponse uif = new ApplyUserInfoResponse();
        uif.setUserId(supportInfo.getApplyUserId());
        uif.setMail(supportInfo.getApplyUserMail());
        uif.setPhone(supportInfo.getApplyUserPhone());
        uif.setUserName(supportInfo.getApplyUserName());
        uif.setDepartId(supportInfo.getApplyUserDepartId());
        uif.setOrganId(supportInfo.getApplyUserOrganId());
        uif.setOrganChainName(supportInfo.getApplyUserDepartChainName());
        String organChainName = supportInfo.getApplyUserDepartChainName();
        if (UtilValidate.isNotEmpty(organChainName)) {
            String[] names = organChainName.split(">");
            if (names.length >= 2) {
                uif.setDepartName(names[names.length-1]);
                uif.setOrganName(names[0]);
            }
        }
        return uif;
    }

    /**
     * 分页查询已办任务，控制权限
     * @param params
     * @param start
     * @param pageSize
     * @return
     */
    public Page<SupportInfoDTO> fineshSupportInfo(Map<String,Object> params,String userId,String userLoginId,int start,int pageSize){
        if (!flowSecuritySerivice.isControl(userLoginId)) {
                 params.put("userId",userId);
                return dao.queryPage(SupportInfo.class.getName()+".allFineshedSupportInfo",params,start,pageSize);
        } else {
            Set<String> dataObjectIds = flowSecuritySerivice.findDataObjectIds(userLoginId);
            // 需要区分 支撑单表 和 支撑表
            if (UtilValidate.isNotEmpty(dataObjectIds)) {
                params.put("dataObjectIds",dataObjectIds);
            }else {
                params.put("userId",userId);
            }
            return dao.queryPage(SupportInfo.class.getName()+".allFineshedSupportInfo",params,start,pageSize);
        }
    }

}
